import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Dialog, Drawer, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useRef, useState } from 'react';
import { column } from './stores/definitions';
import PortForm from './components/PortForm';

const Region = () => {
  return (
    <TauPage className="page-container-2">
      <RegionList />
    </TauPage>

  );
};

const RegionList = observer(() => {
  const { portStore: store } = useStore();
  const [modal, setModal] = useState([]);
  const objRef = useRef();

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { ...searchArgs } = params.values;
    store.search = {
      ...searchArgs,
    };
  };

  // 点击打开添加
  const handleOpenAdd = () => {
    setModal(['add']);
  };

  // 点击打开查看
  const handleOpenView = (region) => {
    objRef.current = region;
    setModal(['view']);
  };

  // 点击打开编辑
  const handleOpenEdit = (region) => {
    objRef.current = region;
    setModal(['edit']);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 新增订单数据提交
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        // eslint-disable-next-line no-param-reassign
        await store.create(toJS(result));
        Message.success({ content: t`创建成功` });
      } catch (e) {
        Message.error({ content: t`创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleRemove = (region) => {
    Dialog.confirm({
      content: t`删除【${region.name}】吗？`,
      onOk: () => store.remove(region),
    });
  };


  return (
    <div className="main-content" >
      <TauActionPanel
        className="action-panel"
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-placeRegion',
            title: t`添加口岸`,
            type: 'primary',
            onClick: handleOpenAdd,
          },
        ]}
        keywordSearch={{
          placeholder: t`请输入关键字搜搜`,
        }}
      />
      <div className="content">
        <TauTable
          primaryKey="itemId"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.regions)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('itemId', { width: 82, cell: (v, _, region) => <Button type="primary" text onClick={() => handleOpenView(region)}>{v}</Button> }),
            column('name', {}),
            column('disabled', {}),
            column('sortWeight', { width: 88 }),
            column('ts', { sortable: true }),
            {
              title: t`操作`,
              dataIndex: 'regionNumber',
              width: 180,
              cell: (_, __, region) => (
                <>
                  <Button text type="primary" onClick={() => handleOpenEdit(region)} >{t`编辑`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" onClick={() => handleRemove(region)} >{t`删除`}</Button>
                </>),
            },
          ]}
        />
      </div>
      <Drawer
        visible={!!modal[0]}
        title={modal[0] === 'add' ? t`添加口岸` : t`修改口岸【${objRef.current?.name}】`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="700px"
      >
        <PortForm
          regionId={objRef.current?.itemId}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>
    </div>
  );
});

export default Region;
